#!/bin/bash

set -e

# Resolve compose file
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml"

echo "📦 Using compose file: $COMPOSE_FILE"
export COMPOSE_FILE="$COMPOSE_FILE"

echo "🧹 Cleaning up any existing stack (containers, orphans)..."
docker-compose down -v --remove-orphans || true

# Remove any leftover containers with conflicting names
echo "🧹 Removing leftover named containers if exist..."
docker rm -f wwjcloud-redis >/dev/null 2>&1 || true
docker rm -f wwjcloud-mysql >/dev/null 2>&1 || true
docker rm -f wwjcloud-nestjs >/dev/null 2>&1 || true

if [ "$SKIP_BUILD" = "1" ]; then
  echo "⏭️  Skipping image builds (using local images). Set SKIP_BUILD=0 to force build."
else
  echo "🚀 Building images (backend, admin)..."
  docker-compose build nestjs-backend admin-frontend
fi

echo "🧩 Starting MySQL and Redis..."
docker-compose up -d mysql redis

echo "⏳ Waiting for DB services to be ready..."
sleep 20

echo "🚀 Starting backend..."
if [ "$SKIP_BUILD" = "1" ]; then
  docker-compose up -d --no-build nestjs-backend
else
  docker-compose up -d nestjs-backend
fi

echo "⏳ Waiting for backend health..."
ATTEMPTS=0
until curl -sf http://localhost:3000/health > /dev/null 2>&1 || [ $ATTEMPTS -ge 15 ]; do
  ATTEMPTS=$((ATTEMPTS+1))
  sleep 4
done

echo "🚀 Starting admin frontend..."
if [ "$SKIP_BUILD" = "1" ]; then
  docker-compose up -d --no-build admin-frontend
else
  docker-compose up -d admin-frontend
fi

echo "⏳ Waiting for admin to be ready..."
sleep 15

echo "✅ Services are up."
echo "🌐 Admin: http://localhost"
echo "🔧 API:   http://localhost:3000"

echo "📊 Status:"
docker-compose ps

echo "📦 Docker containers:"
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"


